//package com.ruoyi.kangqiao.utils.mqtt;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.ruoyi.common.utils.DateUtils;
//import com.ruoyi.common.utils.StringUtils;
//import com.ruoyi.kangqiao.domain.CgWorkCard;
//import com.ruoyi.kangqiao.domain.CgWorkCardRecords;
//import com.ruoyi.kangqiao.domain.Rtls;
//import com.ruoyi.kangqiao.domain.Topic;
//import com.ruoyi.kangqiao.service.ICgWorkCardRecordsService;
//import com.ruoyi.kangqiao.service.ICgWorkCardService;
//import com.ruoyi.kangqiao.utils.CoordinateTransform;
//import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
//import org.eclipse.paho.client.mqttv3.MqttCallback;
//import org.eclipse.paho.client.mqttv3.MqttClient;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.nio.charset.StandardCharsets;
//import java.util.*;
//import java.util.concurrent.CompletableFuture;
//import java.util.concurrent.Executors;
//
//@Component
//public class PushCallback implements MqttCallback {
//    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);
//
//    @Autowired
//    @Lazy
//    private MqttConfig mqttConfig;
//
//    @Autowired
//    private ICgWorkCardService cgWorkCardService;
//
//    @Autowired
//    private ICgWorkCardRecordsService cgWorkCardRecordsService;
//
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//    //获取平均坐标点
//    private final Map<String, List<CgWorkCardRecords>> map = new HashMap<>();
//    //获取工牌 防止频繁向数据读取数据
//    private Map<String, CgWorkCard> dice = new HashMap<>();
//    //用于存入定量工牌轨迹记录的集合 然后将数据转嫁给List1  清空list
//    private final List<CgWorkCardRecords> list = new ArrayList<>();
//    //用于批量插入的集合  一次性插入数据库
//    private final List<CgWorkCardRecords> list1 = new ArrayList<>();
//    private MqttClient client;
//    private String _topic;
//    private String _qos;
//    private String _msg;
//
//    public PushCallback(MqttConfig mqttConfig,
//                        ICgWorkCardService cgWorkCardService,
//                        ICgWorkCardRecordsService cgWorkCardRecordsService,
//                        StringRedisTemplate redisTemplate) {
//
//        this.mqttConfig = mqttConfig;
//        this.cgWorkCardService = cgWorkCardService;
//        this.cgWorkCardRecordsService = cgWorkCardRecordsService;
//        this.redisTemplate = redisTemplate;
//
//        List<CgWorkCard> cgWorkCards = cgWorkCardService.selectCgWorkCardList(null);
//        if (Objects.nonNull(cgWorkCards)) {
//            for (CgWorkCard cgWorkCard : cgWorkCards) {
//                dice.put(cgWorkCard.getDeviceCode(), cgWorkCard);
//            }
//        }
//    }
//
//    @Override
//    public void connectionLost(Throwable throwable) {
//        // 连接丢失后，一般在这里面进行重连
//        logger.info("连接断开，可以做重连");
//        if (client == null || !client.isConnected()) {
//            mqttConfig.getMqttPushClient();
//        }
//    }
//
//    public CompletableFuture<Void> processData(String message) {
//        return CompletableFuture.supplyAsync(() -> {
//            Topic topic = JSONObject.parseObject(message, Topic.class);
//            processTopic(topic);
//            return null;
//        }, Executors.newCachedThreadPool());
//    }
//
//    // 处理Topic对象
//    public void processTopic(Topic topic) {
//        CgWorkCard cgWorkCard = dice.get(topic.getDeviceId());
//        //判断工牌是否存在||工牌是否绑定队员
//        if (cgWorkCard == null) {
//            logger.error("工牌不存在");
//        } else if (StringUtils.isEmpty(cgWorkCard.getMemberCode())) {
//            logger.error("未绑定队员:{}", cgWorkCard.getDeviceCode());
//        }
//        logger.debug("工牌存在且有队员");
//
//        //判断当前工牌是否与数据中匹配
//        if (map.containsKey(topic.getDeviceId())) {
//            List<CgWorkCardRecords> topics = map.get(topic.getDeviceId());
//            CgWorkCardRecords records = new CgWorkCardRecords().convert(topic);
//            topics.add(records);
//            map.put(topic.getDeviceId(), topics);
//
//            //如果记录满足3条则处理所有的定位 然后清除相关记录
//            if (topics.size() >= 3) {
//                double sumLongitude = 0;
//                double sumLatitude = 0;
//                //获取经度和纬度
//                for (CgWorkCardRecords cwcr : topics) {
//                    String[] split = cwcr.getPosition().split(",");
//                    sumLongitude += Double.parseDouble(split[0]);
//                    sumLatitude += Double.parseDouble(split[1]);
//                }
//                // 计算平均经纬度
//                double centerLongitude = sumLongitude / 3;
//                double centerLatitude = sumLatitude / 3;
//
//                //坐标系转化,wgs84转为gcj02,centerLongitude是经度,centerLatitude是纬度
//                double[] doubles = CoordinateTransform.transformWGS84ToGCJ02(centerLongitude, centerLatitude);
//                String str = doubles[0] + "," + doubles[1];
//
//                records.setPosition(str);
//                records.setCreateTime(DateUtils.getNowDate());
//                records.setMemberCode(cgWorkCard.getMemberCode());
//                list.add(records);
//                try {
//                    redisTemplate.opsForValue().set(records.getDeviceCode(), JSON.toJSONString(records));
//                } catch (Exception e) {
//                    // 处理异常
//                    logger.info("当前工牌转成Json数据异常", e);
//                }
//                //将集合中的数据存储
//                map.remove(topic.getDeviceId());
//            }
//            if (list.size() >= 32) {
//                list1.addAll(list);
//                list.clear();
//                logger.info("集合已存满32条数据");
//                cgWorkCardRecordsService.saveBatch(list1);
//                list1.clear();
//                List<CgWorkCard> cgWorkCards = cgWorkCardService.selectCgWorkCardList(null);
//                if (Objects.nonNull(cgWorkCards)) {
//                    for (CgWorkCard card : cgWorkCards) {
//                        dice.put(card.getDeviceCode(), card);
//                    }
//                }
//            }
//        } else {
//            List<CgWorkCardRecords> topics = new ArrayList<>();
//
//            CgWorkCardRecords records = new CgWorkCardRecords().convert(topic);
//            records.setMemberCode(cgWorkCard.getMemberCode());
//            topics.add(records);
//            map.put(topic.getDeviceId(), topics);
//        }
//    }
//
//    // 处理Rtls对象
//    private void processRtls(Rtls rtls) {
//
//        CgWorkCard cgWorkCard = dice.get(rtls.getDeviceId());
//
//        if (Objects.isNull(cgWorkCard) || cgWorkCard.getMemberCode() == null) {
//            logger.info("找不到相关工牌，当前工牌编号为：{}", rtls.getDeviceId());
//            return;
//        }
//
//        if (rtls.getType() == 3) {
//            cgWorkCard.setType(rtls.getValue());
//            dice.put(rtls.getDeviceId(), cgWorkCard);
//        }
//    }
//
//    @Override
//    public void messageArrived(String topic, MqttMessage mqttMessage) {
//        // subscribe后得到的消息会执行到这里面
////        logger.info("接收消息主题 : " + topic);
////        logger.info("接收消息Qos : " + mqttMessage.getQos());
//        // 解码消息内容
//        String message = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
//
//        logger.info("接收消息内容 : " + message);
//
//        _topic = topic;
//        _qos = mqttMessage.getQos() + "";
//        _msg = new String(mqttMessage.getPayload());
//
//        // 处理消息
//        processData(message);
//    }
//
//    @Override
//    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//        logger.info("消息发送完成：" + iMqttDeliveryToken.isComplete());
//    }
//
//}
